package com.app.yc.ifapp;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.app.yc.ifapp.adapter.MyBaseExpandableListAdapter;
import com.app.yc.ifapp.asynctask.WebApiRequest;
import com.app.yc.ifapp.asynctask.WebApiRequestContext;
import com.app.yc.ifapp.entity.ApiResult;
import com.app.yc.ifapp.entity.Field;
import com.app.yc.ifapp.entity.Room;
import com.app.yc.ifapp.entity.Term;
import com.app.yc.ifapp.entity.UserInfo;
import com.app.yc.ifapp.utils.ApiUtils;
import com.app.yc.ifapp.utils.StringUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class IntelligentControlActivity extends Activity {

    UserInfo mUserInfo;
    String url;
    List<Room<Term>> mList_Room_Terms;
    Drawable img_room_class;
    Drawable img_room_dormitory;
    Drawable img_room_function;
    Drawable img_room_laboratory;
    Drawable img_room_office;
    Drawable img_term_access;
    Drawable img_term_light_bulb;
    Drawable img_term_curtains;
    Drawable img_term_fan;
    Drawable img_term_computer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_intelligent_control);

        mUserInfo = getIntent().getParcelableExtra("user");
        url = getIntent().getStringExtra("url");

        //先获取到各种图标
        img_room_class = ContextCompat.getDrawable(this, R.mipmap.room_class);
        img_room_dormitory = ContextCompat.getDrawable(this, R.mipmap.room_dormitory);
        img_room_function = ContextCompat.getDrawable(this, R.mipmap.room_function);
        img_room_laboratory = ContextCompat.getDrawable(this, R.mipmap.room_laboratory);
        img_room_office = ContextCompat.getDrawable(this, R.mipmap.room_office);
        img_term_access = ContextCompat.getDrawable(this, R.mipmap.term_access);
        img_term_light_bulb = ContextCompat.getDrawable(this, R.mipmap.term_light_bulb);
        img_term_curtains = ContextCompat.getDrawable(this, R.mipmap.term_curtains);
        img_term_fan = ContextCompat.getDrawable(this, R.mipmap.term_fan);
        img_term_computer = ContextCompat.getDrawable(this, R.mipmap.term_computer);

        //获取并缩放左箭头
        Drawable drawable = ContextCompat.getDrawable(this, R.mipmap.back_arrow);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth() / 3,
                drawable.getIntrinsicHeight() / 3);
        //获取到控件
        TextView back = (TextView) findViewById(R.id.intelligent_control_back);
        //设置右箭头
        back.setCompoundDrawables(drawable, null, null, null);
        back.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });

        WebApiRequest request = new WebApiRequest();
        request.setAsyncTaskCallBack(new WebApiRequest.AsyncTaskCallBack() {

            @Override
            public void onTaskOver(String result) {

                if (TextUtils.isEmpty(result)) {
                    Toast.makeText(IntelligentControlActivity.this, R.string.error_api_fail,
                            Toast.LENGTH_SHORT).show();
                    return;
                }

                mList_Room_Terms = getData(result);

                if (mList_Room_Terms == null || mList_Room_Terms.size() <= 0) {
                    Toast.makeText(IntelligentControlActivity.this, R.string.error_not_relation_room,
                            Toast.LENGTH_SHORT).show();
                    return;
                }

                //使用适配器绑定数据
                MyBaseExpandableListAdapter<Room<Term>, Term> adapter =
                        new MyBaseExpandableListAdapter<>(IntelligentControlActivity.this,
                                R.layout.item_room,
                                R.layout.item_term,
                                mList_Room_Terms,
                                new MyBaseExpandableListAdapterCallback());
                ExpandableListView listView = (ExpandableListView) findViewById(R.id.list_room_terms);
                listView.setAdapter(adapter);
            }
        });

        try {
            //构造请求登录参数
            String params = "?user_Id" + "=" +
                    URLEncoder.encode(mUserInfo.getUser_Id(), "UTF-8");
            request.execute(url + ApiUtils.GET_TERMS + params, StringUtils.EMPTY);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(IntelligentControlActivity.this, R.string.error_api_fail,
                    Toast.LENGTH_SHORT).show();
        }
    }

    private List<Room<Term>> getData(String json) {
        try {
            Gson gson = new Gson();
            ApiResult<List<Room<Term>>> apiResult = gson.fromJson(json,
                    new TypeToken<ApiResult<List<Room<Term>>>>() {
                    }.getType());
            if (apiResult != null && apiResult.getResult()) {
                if (apiResult.getData() != null && apiResult.getData().size() > 0) {
                    mList_Room_Terms = apiResult.getData();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mList_Room_Terms;
    }

    private class MyBaseExpandableListAdapterCallback
            implements MyBaseExpandableListAdapter.Callback<Room<Term>, Term> {

        @Override
        public void getGroupView(int i, View v, Room<Term> group) {

            TextView tv_name = (TextView) v.findViewById(R.id.room_name);
            TextView tv_type = (TextView) v.findViewById(R.id.room_type);
            ImageView iv_image = (ImageView) v.findViewById(R.id.room_image);
            tv_name.setText(group.getRoom_Name());
            tv_type.setText(group.getRoom_Type());
            iv_image.setTag(i);
            iv_image.setImageDrawable(getRoomImg(group.getRoom_Type()));

            List<Term> child = new ArrayList<>();

            for (Term term : group.getTerms()
                    ) {

                switch (term.getTermTypeId()) {
                    case 17:
                        String[] devices = term.getNotes().split("\\|");
                        if (devices.length > 0) {

                            for (int j = 0; j < devices.length; j++) {
                                String[] tType = devices[j].split(":");
                                if (tType.length > 2) {
                                    Term t = new Term();
                                    t.setTerm_Id(Integer.toString(j + 1));
                                    t.setTermSn(term.getTermSn());
                                    t.setTermNo(term.getTermNo());
                                    t.setTermTypeId(term.getTermTypeId());
                                    t.setTermType(term.getTermType());
                                    t.setTermName(tType[1]);
                                    t.setNotes(tType[0]);
                                    child.add(t);
                                }
                            }
                        }
                        break;
                    case 4:
                        child.add(term);
                        break;
                }
            }

            group.setChild(child);
        }

        @Override
        public void getChildView(int i, View v, Room<Term> group, Term child) {
            TextView tv_name = (TextView) v.findViewById(R.id.term_name);
            TextView tv_type = (TextView) v.findViewById(R.id.term_type);
            ImageView iv = (ImageView) v.findViewById(R.id.term_image);
            Button bv1 = (Button) v.findViewById(R.id.term_button_1);
            Button bv2 = (Button) v.findViewById(R.id.term_button_2);

            bv1.setTag(R.id.id_term, child);
            bv1.setTag(R.id.id_mode, 1);
            bv1.setOnClickListener(new ControlButtonClick());
            bv1.setVisibility(View.VISIBLE);

            bv2.setTag(R.id.id_term, child);
            bv2.setTag(R.id.id_mode, 0);
            bv2.setOnClickListener(new ControlButtonClick());
            bv2.setVisibility(View.VISIBLE);

            tv_name.setText(child.getTermName());
            tv_type.setText(child.getTermType());
            iv.setTag(i);
            Drawable drawable = getTermImg(child.getTermTypeId(), child.getNotes());
            iv.setImageDrawable(drawable);

            switch (child.getTermTypeId()) {
                case 17:
                    if (child.getTermName() != null &&
                            (child.getTermName().contains("窗帘") ||
                                    child.getTermName().contains("幕布"))) {
                        if (child.getTermName().contains("降") ||
                                child.getTermName().contains("开")) {
                            bv1.setText(R.string.text_put_down);
                        } else if (child.getTermName().contains("升") ||
                                child.getTermName().contains("关")) {
                            bv1.setText(R.string.text_put_up);
                        } else {
                            bv1.setText(R.string.text_open);
                        }
                        bv2.setText(R.string.text_stop);
                    } else {
                        bv1.setText(R.string.text_open);
                        bv2.setText(R.string.text_close);
                    }
                    break;
                case 4:
                    bv1.setText(R.string.text_open_door);
                    bv2.setVisibility(View.GONE);
                    break;
                default:
                    bv1.setText(R.string.text_open);
                    bv2.setText(R.string.text_close);
                    break;
            }
        }
    }

    /*
     * 控制按钮点击事件
     */
    private class ControlButtonClick implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            Term term = (Term) v.getTag(R.id.id_term);
            int mode = (int) v.getTag(R.id.id_mode);

            String taskApi = StringUtils.EMPTY;
            String params = StringUtils.EMPTY;

            try {

                switch (term.getTermTypeId()) {
                    case 17:
                        taskApi = ApiUtils.TASK_SWITCH_CONTROL;
                        params = "?user_Id=" + URLEncoder.encode(mUserInfo.getUser_Id(), "UTF-8") +
                                "&sn=" + term.getTermSn() +
                                "&way=" + term.getTerm_Id() +
                                "&mode=" + Integer.toString(mode) +
                                "&type=" + term.getNotes();
                        break;
                    case 4:
                        taskApi = ApiUtils.TASK_OPEN_DOOR;
                        params = "?user_Id=" + URLEncoder.encode(mUserInfo.getUser_Id(), "UTF-8") +
                                "&sn=" + term.getTermSn() +
                                "&mode=1" +
                                "&delay=10" +
                                "&type=4";
                        break;
                }

                if (!StringUtils.isNullOrEmpty(taskApi)) {
                    WebApiRequestContext<Button> request = new WebApiRequestContext<>((Button) v);
                    request.setAsyncTaskCallBack(new WebApiRequestContext.AsyncTaskCallBack<Button>() {

                        @Override
                        public void onTaskOver(String result, Button context) {
                            context.setEnabled(true);

                            try {
                                Gson gson = new Gson();
                                ApiResult<List<Field>> apiResult = gson.fromJson(result,
                                        new TypeToken<ApiResult<List<Field>>>() {
                                        }.getType());
                                if (apiResult == null) {
                                    Toast.makeText(IntelligentControlActivity.this,
                                            R.string.error_api_fail,
                                            Toast.LENGTH_SHORT).show();
                                    return;
                                }

                                if (apiResult.getMessage() != null) {
                                    Toast.makeText(IntelligentControlActivity.this,
                                            apiResult.getMessage(),
                                            Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(IntelligentControlActivity.this,
                                            R.string.error_api_fail,
                                            Toast.LENGTH_SHORT).show();
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                    v.setEnabled(false);
                    request.execute(url + taskApi + params, StringUtils.EMPTY);
                }
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(IntelligentControlActivity.this, R.string.error_api_fail,
                        Toast.LENGTH_SHORT).show();
            }
        }
    }

    /*
     * 获取房间的图标
     */
    private Drawable getRoomImg(String type) {
        switch (type) {
            case "教室": return img_room_class;
            case "实验室": return img_room_laboratory;
            case "宿舍": return img_room_dormitory;
            case "办公室": return img_room_office;
            case "功能室": return img_room_function;
        }

        return  null;
    }

    /*
     * 获取设备的图标
     */
    private Drawable getTermImg(int type, String note) {
        switch (type) {
            case 4 :
                return img_term_access;
            case 17:
                switch (note) {
                    case "1": return img_term_light_bulb;
                    case "2": return img_term_fan;
                    case "3": return img_term_computer;
                    case "4": return img_term_curtains;
                }
                break;
        }

        return  null;
    }
}
